package com.itheima.weirpc.protocol;

import com.itheima.weirpc.serializer.Serializer;
import com.itheima.weirpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;
import java.io.Serial;

/**
 * ClassName: ProtocolMessageEncoder
 * Package: com.itheima.weirpc.protocol
 * Description:
 *
 * @Author 看到风
 * @Create 2024/12/12 9:58
 * @Version 1.0
 */
public class ProtocolMessageEncoder {
    /**
     * 编码
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage)throws IOException{
        if(protocolMessage==null||protocolMessage.getHeader()==null){
            return Buffer.buffer();
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();
        //一次向缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        buffer.appendByte((header.getMagic()));
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());
        //获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if(serializerEnum==null){
            throw new RuntimeException("序列化协议不存在");
        }
        //获取序列化实例
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        //写入body 长度和数据
        buffer.appendInt((bodyBytes.length));
        buffer.appendBytes(bodyBytes);
        return buffer;
    }
}
